package com.blackfish.factory;

import com.blackfish.bag.BagService;
import com.blackfish.common.model.BagBelong;
import com.blackfish.common.model.Device;
import com.blackfish.common.model.User;
import com.blackfish.common.repcode.ErrorMsg;
import com.blackfish.common.untils.FileUntil;
import com.blackfish.common.untils.ShaUntil;
import com.blackfish.common.untils.UnZipUtil;
import com.blackfish.device.DeviceService;
import com.blackfish.factory.product.DeviceProduct;
import com.blackfish.factory.product.ModuleProduct;
import com.blackfish.module.ModuleService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.upload.UploadFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FactoryController extends Controller {
    static final Cache eventCache = Redis.use("event");
    static final FactoryService service = new FactoryService();
    static final BagService bagService = new BagService();
    static final DeviceService deviceService = new DeviceService();
    static final ModuleService moduleService = new ModuleService();
    static final ShaUntil shaUntil = new ShaUntil();
    static final UnZipUtil unZipUtil = new UnZipUtil();

    public void index() {
        render("./index.html");
    }


    public void createApp() {
        UploadFile icoFile = getFile("ico");
        UploadFile appFile = getFile("app");
        String appName = getPara("appName");
        User user = (User) getSession().getAttribute("User");
        String pathName = shaUntil.getPathName(appName, (user != null) ? user.getName() : "");

        String fileName = appFile.getFileName();
        File file = appFile.getFile();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        File fileDir = new File(file.getPath().split(file.getName())[0]+pathName);
        if(!fileDir.exists()){
            fileDir.mkdir();
        }
        File zip = new File(fileDir.getPath()+"\\"+fileName);
        appFile.getFile().renameTo(zip);


        String ico_suffix = icoFile.getFileName().substring(icoFile.getFileName().lastIndexOf("."));
        File ico = new File("F:\\Object\\Java\\jfBlackFish-web\\WebRoot\\factory\\product\\ico\\"+appName+ico_suffix);
        icoFile.getFile().renameTo(ico);


        if (suffix.equals("zip")) {
            String dir = bagService.findDirByName(fileName);
            if (dir == null) {
                try {
                    unZipUtil.unzip(file.getName(), fileDir.getPath()+"\\");
                    // TODO 取出json文件分析新建控件
                    int bagId = service.createBag(appName, pathName, user);
                    if (bagId != 0) {
                        eventCache.set(user.getName() + ":" + appName, "1");
                        renderJson("{state:\"ok\"}");
                    } else {
                        renderJson("{state:\"error\"}");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    renderJson("{state:\"error\"}");
                }
            } else {
                renderJson("{state:\"error\"}");
            }
        } else {
            renderJson("{state:\"error\"}");
        }
        // file.delete();
        // zip.delete();
    }

    public void initApp() {
        if (getRequest().getMethod() == "GET") {
            User user = (User) getSession().getAttribute("User");

            // 获得session中的需要初始化bag的路径
            String bagBelongId = getPara("bagBelong");
            BagBelong bagBelong = bagService.getBagBelongById(Integer.valueOf(bagBelongId));
            if(bagBelong==null){
                return ;
            }
            String bagPath = bagBelong.getStaticdir();
            BagService bagService = new BagService();

            ;//getPara("pathName");
            bagPath = "F:\\Object\\Java\\jfBlackFish-web\\WebRoot\\factory\\product\\"+bagPath;
            // 在路径下获得init文件夹下的device.json

            String deviceJsonStr = null;
            try {
                deviceJsonStr = FileUntil.FileInputStreamDemo(bagPath + "/init/device.json");
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (deviceJsonStr == null) {
                renderJson("{state:" + ErrorMsg.NODATA + "}");
            } else {
                // 生成列表返回
                Gson gson = new Gson();
                List<DeviceProduct> devices = null;
                try {
                    devices = gson.fromJson(deviceJsonStr, new TypeToken<List<DeviceProduct>>() {
                    }.getType());
                } catch (Exception e) {
                    devices = null;
                }
                if (devices != null) {
                    setAttr("bagDir", bagPath);
                    setSessionAttr(bagPath, devices);
                }


                setAttr("devices", devices);
                setAttr("bagBelong",bagBelongId);
                render("initview.html");
            }
        } else {
            String devcesKeys = getPara("devcesKeys");
        }
    }

    public void product(){
        String bagPath = getPara("bagPath");
        render("./product/"+bagPath+"/html/index.html");
    }

    public void updateApp() {
        User user =  (User)getSession().getAttribute("User");
        String bagBelongId = getPara("bagBelong");
        BagBelong bagBelong = bagService.getBagBelongById(Integer.valueOf(bagBelongId));
        String bagPath = bagBelong.getStaticdir();
        String bagDir = "F:\\Object\\Java\\jfBlackFish-web\\WebRoot\\factory\\product\\"+bagPath;
        List<DeviceProduct> devicePs = (List<DeviceProduct>) getSession().getAttribute(bagDir);
        List<Device> devices = new ArrayList<Device>();

        Map<String,List<Device>> deviceMap = new HashMap<String,List<Device>>();
        for (DeviceProduct deviceP : devicePs) {
            String key = getPara(deviceP.name);
            Device dev = deviceService.creatDevice(deviceP.name, key,user.getId());
            if(dev==null){
                renderJson("{\"state\"=\"ERROR\",\"msg\"=\"Key Error\"}");
                return;
            }
            devices.add(dev);
            if(deviceMap.get(deviceP.flashName)==null){
                deviceMap.put(deviceP.flashName,new ArrayList<>());
            }
            deviceMap.get(deviceP.flashName).add(dev);
        }
        if(deviceService.saveDevice(devices,user.getId())==false){
            renderJson("{\"state\"=\"ERROR\",\"msg\"=\"Save Error\"}");
            return ;
        }

        try {
            String moduleJson = FileUntil.BufferedReaderDemo(bagDir + "/init/module.json");
            Gson gson = new Gson();
            List<ModuleProduct> moduleProducts = gson.fromJson(moduleJson, new TypeToken<List<ModuleProduct>>() {
            }.getType());
            for (ModuleProduct moduleProduct : moduleProducts) {
                moduleService.createModule(moduleProduct,deviceMap);
            }
        } catch (IOException e) {
            renderJson("{\"state\"=\"ERROR\",\"msg\"=\"SaveModule Error\"}");
            e.printStackTrace();
            return ;
        } catch (Exception e) {
            renderJson("{\"state\"=\"ERROR\",\"msg\"=\"SaveModule Error\"}");
            e.printStackTrace();
            return ;
        }

        //删除session中初始化bag
        bagBelong.setVersion(1).update();

        renderJson("{\"state\":\"OK\",\"bagId\":"+bagBelong.getBagId()+"}");
    }


}
